package com.example;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;

@Slf4j
@Controller
public class IndexController {

    @GetMapping("/login")
    public String login() {
        log.info("-------------> login");
        return "login";
    }

    @GetMapping({"/", "", "/index"})
    public String index() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("用户----------->{}", authentication.getPrincipal());
        return "index";
    }

    @ResponseBody
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/admin")
    public Object admin() {
        return "说明有admin角色权限";
    }

    @ResponseBody
    @PreAuthorize("hasRole('ROLE_VIP')")
    @GetMapping("/vip")
    public Object vip() {
        return "说明有vip角色权限";
    }


    @GetMapping({"/test"})
    public String test() {

        String username = "user";
        String pass = "1";

        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(new IPasswordEncoder());

        ArrayList<AuthenticationProvider> providers = new ArrayList<>();
        providers.add(provider);

        AuthenticationManager am = new ProviderManager(providers);


        Authentication token = new UsernamePasswordAuthenticationToken(username, pass);
        Authentication authenticate = am.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authenticate);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("用户----------->{}", authentication.getPrincipal());
        return "index";
    }
}
